//
//  MYPublishEditVC.m
//  MuYing
//
//  Created by tbb on 2019/8/14.
//  Copyright © 2019 TBB. All rights reserved.
//

#import "MYPublishEditVC.h"
#import "MYPublishEditCategoryVC.h"
#import "MYPublishEditAssociatedGoodsVC.h"
#import "MYPublishEditCategoryModel.h"
#import "MYPublishEditProductModel.h"
#define KTAG_DELETEBTN_BASE 11100
@interface MYPublishEditVC ()
@property (nonatomic, strong) MYPublishImageTagTopView * topView;
@property (nonatomic, strong) NSMutableArray * goodsArr;
@property (nonatomic, copy) NSArray * classArr;
@property(nonatomic,assign) BOOL statusHiden;

@property (nonatomic, strong) QMUITextField * titleTextField;
@property (nonatomic, strong) QMUITextView * contentTextView;
@end

@implementation MYPublishEditVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

-(void)setupView {
    [super setupView];
    [self.view addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kHeight_Top_SafeArea);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(44);
    }];
    
    self.topView.layer.shadowColor=[UIColor blackColor].CGColor;
    self.topView.layer.shadowOffset=CGSizeMake(0, 0);
    self.topView.layer.shadowOpacity=0.1;
    self.topView.layer.shadowRadius=4;
    
    self.listTableView.backgroundColor = kAPPTABLEVIEW_BG_COLOR;
    self.listTableView.frame = CGRectMake(0, kHeight_Top_SafeArea+44, kYQPScreenWidth, kYQPScreenHeight-44-kHeight_Botton_SafeArea-kHeight_Top_SafeArea);
    kYQREGISTERTABLEVIEWNIBCELL(@"MYPublishEditTitleCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"MYPublishEditContentCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"MYPublishEditSelectClassCell")
    kYQREGISTERTABLEVIEWCELL([MYPublishEditCollCell class])
    kYQREGISTERTABLEVIEWNIBCELL(@"MYShopCarCell")
    kYQREGISTERTABLEVIEWCHeaderFooter([MYPublishEditGoodsHeader class]);
    kYQREGISTERTABLEVIEWCHeaderFooter([MYPublishEditGoodsFooter class]);
    
}
#pragma mark -- 发布
-(void)publishAction:(UIButton *)sender {
    
    NSString *title = self.titleTextField.text;
    if ([title removeStringSpace].length == 0) {
        kMBMesHUD(kYQLS(@"请输入标题"));
        return;
    }
    
    NSString *content = self.contentTextView.text;
    if ([content removeStringSpace].length == 0) {
        kMBMesHUD(kYQLS(@"请输入内容"));
        return;
    }
    
    if(self.classArr.count == 0) {
        kMBMesHUD(kYQLS(@"请选择分类"));
        return;
    }
    
    NSMutableDictionary *par = [NSMutableDictionary dictionary];
    
    NSMutableArray *channelIdList = @[].mutableCopy;
    NSString *typeStr = @"";
    for (MYPublishEditClassModel *classModel in self.classArr) {
        typeStr = classModel.type;
        [channelIdList addObject:classModel.channelId];
    }
    
    par[@"channelIdList"] = channelIdList.copy;
    par[@"content"] = content;
    par[@"title"] = title;
    par[@"imageList"] = self.publishImageUrlArr.copy;
    par[@"type"] = typeStr;
    
    NSMutableArray *produceIdArr = @[].mutableCopy;
    for (MYPublishEditProductGoodsModel *produceModel in self.goodsArr) {
        [produceIdArr addObject:produceModel.productId];
    }
    par[@"produceIdList"] = produceIdArr;
    
    YQSHOWLOADINGTIPS(@"正在发布")
    [YQPNetWorkingManager sendPostRequest:kPOST_Publice_Invitation_URL parameters:par success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            YQUITIPSSUCCEED(kYQLS(@"发布成功"));
            [self.navigationController dismissViewControllerAnimated:true completion:nil];
        }else{
            kMBMesHUD(responseObject.msg);
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        kMBMesHUD(error);
        YQHIDELOADINGTIPS
    }];
    
}
-(void)deleteGoodsAction:(UIButton *)sender {
    NSInteger row = sender.tag - KTAG_DELETEBTN_BASE;
    [self.goodsArr removeObjectAtIndex:row];
    [self.listTableView reloadData];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }else if (section == 3) {
        return self.goodsArr.count;
    }
    return 1;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            MYPublishEditTitleCell *titleCell = [tableView dequeueReusableCellWithIdentifier:@"MYPublishEditTitleCell"];
            self.titleTextField = titleCell.titleTextFiled;
            return titleCell;
        }else{
            MYPublishEditContentCell *contentCell = [tableView dequeueReusableCellWithIdentifier:@"MYPublishEditContentCell"];
            self.contentTextView = contentCell.contentTextView;
            return contentCell;
        }
    }else if (indexPath.section == 1) {
        MYPublishEditCollCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYPublishEditCollCell"];
        cell.imageArr = self.publishImageArr.copy;
        cell.imageUrlArr = self.publishImageUrlArr.copy;
        return cell;
    }else if(indexPath.section == 2) {
        MYPublishEditSelectClassCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYPublishEditSelectClassCell"];
//        cell.categoryLb.text = self.classStr;
        NSMutableArray *titleArr = @[].mutableCopy;
        for (MYPublishEditClassModel *classModel in self.classArr) {
            [titleArr addObject:classModel.name];
        }
        cell.categoryLb.text = [titleArr componentsJoinedByString:@","];
        return cell;
    }else{
        
        MYPublishEditProductGoodsModel *productModel = nil;
        if (indexPath.row < self.goodsArr.count) {
            productModel = self.goodsArr[indexPath.row];
        }
        
        MYShopCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopCarCell"];
        cell.lineView.hidden = NO;
                
        [cell.selectBtn setImage:YQIMG(@"PublishEdit_delete_goods_icon") forState:(UIControlStateNormal)];
        [cell.selectBtn setImage:YQIMG(@"PublishEdit_delete_goods_icon") forState:(UIControlStateSelected)];
        cell.titleLb.text = productModel.productName;
        cell.specificationLb.text = @" ";
        cell.priceLb.text = [NSString stringWithFormat:@"￥%@",productModel.price];
        [cell.goodsIcon setImageURL:[NSURL URLWithString:productModel.defaultImage]];
        cell.selectBtn.tag = KTAG_DELETEBTN_BASE + indexPath.row;
        [cell.selectBtn addTarget:self action:@selector(deleteGoodsAction:) forControlEvents:(UIControlEventTouchUpInside)];
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 48;
        }else{
            return 116;
        }
    }else if (indexPath.section == 3) {
        return 124;
    }else if (indexPath.section == 1) {
        CGFloat w = (kYQPScreenWidth - 35) / 4.0;
        NSInteger row = 0;
        if (self.publishImageArr.count % 4 == 0) {
            row = self.publishImageArr.count / 4;
        }else{
            row = (self.publishImageArr.count / 4) + 1;
        }
        return (row * w) + (row - 1) * 7 + 28;
    }
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        MYPublishEditCategoryVC *categoryVC = [[MYPublishEditCategoryVC alloc] init];
        ws(self);
        categoryVC.selectClassBlock = ^(NSArray * _Nonnull classArr) {
            weakself.classArr = classArr;
            [weakself.listTableView reloadData];
        };
        kYQPUSH(categoryVC);
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 3) {
        MYPublishEditGoodsFooter *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYPublishEditGoodsFooter"];
        [footer.selectBtn addTapAction:^(id  _Nonnull sender) {
            if (self.classArr.count == 0) {
                MBSucHUD(kYQLS(@"请选择商品分类"));
                return;
            }
            MYPublishEditAssociatedGoodsVC *goodsVC = [[MYPublishEditAssociatedGoodsVC alloc] init];
            MYPublishEditClassModel *classModle = self.classArr.firstObject;
            goodsVC.parentName = classModle.parentName;
            if (self.goodsArr.count > 0) {
                goodsVC.selectedArr = self.goodsArr;
            }
            goodsVC.selectParentGoodsBlock = ^(NSArray * _Nonnull goodsArr) {
                [self.goodsArr removeAllObjects];
                [self.goodsArr addObjectsFromArray:goodsArr.modelCopy];
                [self.listTableView reloadData];
            };
            kYQPUSH(goodsVC);
        }];
        if (self.goodsArr.count > 0) {
            [footer.selectBtn setTitle:kYQLS(@"继续添加") forState:(UIControlStateNormal)];
        }else{
            [footer.selectBtn setTitle:kYQLS(@"添加") forState:(UIControlStateNormal)];
        }
        return footer;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 3) {
        return 44;
    }
    return 12;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 3) {
        MYPublishEditGoodsHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYPublishEditGoodsHeader"];
        return header;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 3) {
        return 40;
    }
    return 0.001;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end

#pragma mark --lazy
-(MYPublishImageTagTopView *)topView {
    if (!_topView) {
        _topView = [MYPublishImageTagTopView viewFromXib];
        _topView.backgroundColor = UIColor.whiteColor;
        [_topView.backBtn setImage:YQIMG(@"Publish_cancel_icon") forState:(UIControlStateNormal)];
        _topView.tittleLb.text = @"";
        [_topView.nextBtn setTitle:kYQLS(@"发布") forState:(UIControlStateNormal)];
        [_topView.nextBtn addTarget:self action:@selector(publishAction:) forControlEvents:(UIControlEventTouchUpInside)];
        ws(self);
        [_topView.backBtn addTapAction:^(id  _Nonnull sender) {
            [weakself.navigationController dismissViewControllerAnimated:true completion:nil];
        }];
        
    }
    return _topView;
}

-(NSMutableArray *)goodsArr {
    if (!_goodsArr) {
        _goodsArr = [NSMutableArray array];
    }
    return _goodsArr;
}
-(NSMutableArray *)publishImageArr {
    if (!_publishImageArr) {
        _publishImageArr = [NSMutableArray array];
    }
    return _publishImageArr;
}
-(NSMutableArray *)publishImageUrlArr {
    if (!_publishImageUrlArr) {
        _publishImageUrlArr = [NSMutableArray array];
    }
    return _publishImageUrlArr;
}
#pragma mark --lazy end
-(void)setVideoUrl:(NSString *)videoUrl {
    _videoUrl = [videoUrl copy];
    UIImage *image = [UIImage firstFrameWithVideoURL:videoUrl size:self.videoSize];
    if (image) {
        [self.publishImageArr addObject:image];
        //NSUInteger s = [NSDate durationWithVideo:videoUrl];
        [self.listTableView reloadData];
    }else{
        NSLog(@"");
    }
    
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
    [self.view addGestureRecognizer:pan];
    self.statusHiden = YES;
    // 刷新状态栏
    [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
}


-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.statusHiden = NO;
    // 刷新状态栏
    [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
}

- (BOOL)prefersStatusBarHidden{
    return self.statusHiden;
}
@end
